// promise


// 定义状态
const STATUS = {
    PENDING: 'pending',
    FULFILLED: 'fulfilled',
    REJECTED: 'rejected'
}

function resolvePromise(parent, x, resolve, reject) {
    if (parent === x) {
        // 如果返回的结果的promise 是本身，抛出错误
        new Error('same promise')
    }
    if (x instanceof MyPromise) {
        // 如果value 是个 promise,则注册进去
        x.then(resolve, reject)
    } else {
        // 如果不是promise ,直接返回
        resolve(x)
    }
}

class MyPromise {
    status = STATUS.PENDING  // 初始的状态值，默认是等待
    reason = undefined   // 错误信息
    value = undefined    // 保存 的值 
    successCallback = ''  // 存储success 的then 
    failCallback = ''    // 存储错误转态

    constructor(executor) {
        //  立即执行执器
        try {
            executor(this.resolve, this.reject);
        } catch (error) {
            this.reject(error)
        }
    }
    resolve = (value) => {
        // 如果状态 还是pending 则状态改变
        // pending => fulfilled
        if (this.status === STATUS.PENDING) {
            this.status = STATUS.FULFILLED;
            this.value = value;
            this.successCallback && this.successCallback();  //每次then都是返回的新的promise, 没必要变成数组
        }
    }
    reject = (reason) => {
        // pending => rejected
        if (this.status === STATUS.PENDING) {
            this.status = STATUS.REJECTED;
            this.reason = reason;
            this.failCallback && this.failCallback(); //每次then都是返回的新的promise, 没必要变成数组
        }
    }
    then = (successCallback, failCallback) => {
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status === STATUS.FULFILLED) {
                setTimeout(() => {
                    try {
                        let value = successCallback && successCallback(this.value) || this.value;
                        resolvePromise(promise2, value, resolve, reject);
                    } catch (e) {
                        reject(e)
                    }
                }, 0);
            } else if (this.status === STATUS.REJECTED) {
                setTimeout(() => {
                    try {
                        let reason = failCallback && failCallback(this.reason) || this.reason;
                        resolvePromise(promise2, reason, resolve, reject);
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else {
                // 还在等待中
                this.successCallback = () => {
                    setTimeout(() => {
                        try {
                            let value = successCallback && successCallback(this.value) || this.value;
                            resolvePromise(promise2, value, resolve, reject);
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                };
                this.failCallback = () => {
                    setTimeout(() => {
                        try {
                            let reason = failCallback && failCallback(this.reason) || this.reason;
                            resolvePromise(promise2, reason, resolve, reject);
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                }
            }
        })
        return promise2
    }

    static all(array) {
        let result = [];
        let index = 0;  // 用于累加
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    resolve(resolve)
                }
            }
            for (let index = 0; index < array.length; index++) {
                const current = array[index];
                if (current instanceof MyPromise) {
                    // promise 对象
                    current.then(value => addData(i, value), (e) => {
                        reject(e)
                    }); //成功后加个成功回调
                } else {
                    addData(i, current)
                }
            }
        })
    }

    static resolve(value) {
        if (value instanceof MyPromise) return value; // promise 对象则返回promise 对象
        new MyPromise(resolve => resolve(value));
    }

    static reject(reason) {
        if (reason instanceof MyPromise) return reason; // promise 对象则返回promise 对象
        return new MyPromise((resolve, reject) => reject(reason));
    }

    finally(callback) {
        // 添加一个回调就行
        return this.then((value) => {
            // 成功的回调 
            return MyPromise.resolve(callback && callback()).then(() => value);
        }, (reason) => {
            return MyPromise.resolve(callback && callback()).then(() => { throw reason });
        })
    }
    catch(callback) {
        return this.then(undefined, callback);
    }
}


// new MyPromise((resolve, reject) => {
//     resolve(1)
// }).then((value) => {
//     console.log(value)
// })

// MyPromise.resolve(1).then(() => {
//     console.log(1)
// })

// new MyPromise((resolve, reject) => {
//     setTimeout(() => {
//         resolve(1);
//     }, 2000);
// }).then((value) => {
//     console.log(value, 1);
//     return new MyPromise((resolve) => {
//         setTimeout(() => {
//             resolve(43)
//         }, 2000);
//     })
// }).then((value) => {
//     console.log(value, 2)
// })

var promise = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(11)
    }, 10)
}).then((value) => console.log(value)).finally(() => {
    console.log('finally')
})